package com.umb.cs.class1.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.umb.cs.class1.api.BookVO;

public class ParserManager {

	public static List<BookVO> parseMetadata(){
		 List<BookVO> bookList= null;
		 String title = null; 
		try{
				   
			       File inputFile = new File("src/resources/biblio23.txt");
			       StringBuffer contents = new StringBuffer();
			       BufferedReader reader = null; 
			       reader = new BufferedReader(new FileReader(inputFile));
			       String text = null;
			    
				    
			       bookList= new ArrayList<BookVO>();
			       
			     /*********************Begin to parse and write elements into our system ********************/       
			       // The following part is the main process of reading txt file and generating the
			       // corresponding xml file. Its strategy is to use "T" in txt file as the entrance of generating, and use
			       // "W." as the exit. 
			       while ((text = reader.readLine())!= null)
			       {
			    	   	
			       /*******"T" is used as the entrance because it's always the first line of each item***/
				          if(text.startsWith("T"))
				          {     
				        	BookVO b=new BookVO();
				        	
				        	  if(!text.startsWith("T"))
				              {
				                continue;
				              }	            
				        	  title = text.substring(2).trim();
				              /****Remember the standard position of first letter*****/
				              int stand = text.substring(1).replaceFirst("\\w","x").indexOf("x");
				       
				            
				            while ((text = reader.readLine())!= null)
				            {
					              if(text.startsWith("T"))
					              {                 
					            	  title +=" " + text.substring(2).trim();    
					             
					                  //*****ading title to the bookVO 
					            	  b.setTitle(title);
					              }
					              else if(text.startsWith("A"))
					              { 
					                //Create the "Author field", and set value for it.
					                //*****ading AUTHOR to the bookVO 
						            b.setAuthor(Arrays.asList(text.substring(2).trim()));
					                
					              }
					              else if(text.startsWith("K"))
					              {   
						                     
						              //*****ading Keyword to the bookVO 
						                b.setKeyword(text.substring(2).trim());
						                
					              }
					              else if(text.startsWith("U"))
					              { 
					            	  
					            	  uline(text, b);
						            
					              }
					           /***********"W." is used as the exit because it's the last line of each item.***/      
					              else if(text.startsWith("W."))
					              { 
					            	  String[] citations = text.substring(2).trim().split(";");
					                  
					                  for(String citation: citations)
					                  {
					                    b.setCitation(citation);
					                    
					                  }
					                
					                  break;
					              }
					              else if(text.startsWith("W"))
					              { 
					            	  wline(stand, text,b);						                
					              }
						        
				            }
				            bookList.add(b);
				            				           
				          }
				          
			       }
			  
		      
			       System.out.println("Done");
			 
		    }catch (FileNotFoundException e)
		    {
		      e.printStackTrace();
		    } catch (IOException e)
		    {
		      e.printStackTrace();
		    }
		    
		    return bookList;
	}
	
	  public static void uline(String text, BookVO book)
	  {
	    int numCnt = text.replaceFirst("\\(|\\d","1").indexOf("1");
	    int comCnt = text.indexOf(",");
	    int numCnt2 = text.substring(comCnt).replaceFirst("\\d","1").indexOf("1");
	    int lbrCnt = 0;
	    int rbrCnt = 0;
	    int colonCnt = text.indexOf(":");                
	    int ruleCnt;          
	    String volume="";
	    String issue="";
	    String startPage = "";
	    String endPage;
	    String month = text.substring(comCnt+1,comCnt+numCnt2).trim() ;
	    //try to use last 4 digit, modified in Beta4
	    String year = text.substring (text.length()-4).trim();                           
	    String jnlName = text.substring(1,numCnt).trim();       
	    String date = text.substring(comCnt+1);
	    
	    if(text.contains("("))
	    {
	      lbrCnt = text.indexOf("(");
	      rbrCnt = text.indexOf(")");
	      
	      if(lbrCnt>numCnt)
	      { volume= text.substring(numCnt,lbrCnt).trim();}                  
	      issue= text.substring(lbrCnt+1,rbrCnt).trim();   
	    }
	    else { volume =text.substring(numCnt,colonCnt).trim();}    
	    
	    
	    String tmp = text.substring(colonCnt);
	    if(text.contains("-"))
	    {
	      startPage = tmp.substring(1,tmp.indexOf("-")).trim();
	      /**
	       ruleCnt = text.indexOf("-");
	       if(ruleCnt>colonCnt)
	       startPage = text.substring(colonCnt+1,ruleCnt).trim();
	       //else {System.out.println(text);}
	       endPage = text.substring(ruleCnt + 1,comCnt).trim();    
	       **/
	    }
	    else {
	      startPage = tmp.substring(1,tmp.indexOf(",")).trim();
	      /**
	       startPage=tmp.substring(colonCnt+1,comCnt);
	       endPage = startPage;
	       **/
	    } 
	    
	    book.setJournal(jnlName);
	    book.setMonth(month);
	    book.setYear(date);
	    book.setVolume(volume);
	    book.setIssue(issue);
	    book.setProfile(text.substring(1).trim());
	    book.setPage(startPage);
	     	    
	  } 	
	  
	  public static void wline(int stand, String text, BookVO book)
	  {
	    int comp = text.substring(1).replaceFirst("\\w","x").indexOf("x");
	    /*****figure out if it's address line or profile line according to align******/
	    /**if it's address line**/
	    if(comp>stand)
	    {
	      book.setAddress(text.substring(2).trim());
	      
	    }
	    /**if it's profile line**/
	    else
	    {
	      String[] citations = text.substring(1).trim().split(";");
	      
	      for(String citation: citations)
	      {
	        book.setCitation(citation);
	        
	      }
	    }
	  }
	
	
	public static void main(String arg[]){
		List<BookVO> bl = parseMetadata();
		System.out.println(" ");
	}
}
